package io.sundial.repository;

import io.sundial.core.lifecycle.Stateful;
import io.sundial.repository.exception.KeyConflictedException;
import io.sundial.repository.exception.KeyNotFoundException;

import java.util.Collections;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 数据仓储的内存存储实现
 * 基于{@link ConcurrentHashMap}的数据存储实现
 *
 * @author Payne 646742615@qq.com
 * 2018/12/18 10:05
 */
public class Storage<K, V> extends Stateful implements Repository<K, V> {
    private final ConcurrentMap<K, V> storage = new ConcurrentHashMap<>();

    @Override
    public V find(K key) {
        return storage.get(key);
    }

    @Override
    public void save(K key, V value) throws KeyConflictedException {
        V old = storage.putIfAbsent(key, value);
        if (old != null) {
            throw new KeyConflictedException();
        }
    }

    @Override
    public void replace(K key, V value) throws KeyNotFoundException {
        V old = storage.replace(key, value);
        if (old == null) {
            throw new KeyNotFoundException();
        }
    }

    @Override
    public V remove(K key) {
        return storage.remove(key);
    }

    @Override
    public boolean contains(K key) {
        return storage.containsKey(key);
    }

    @Override
    public Enumeration<K> keys() {
        return Collections.enumeration(storage.keySet());
    }

    @Override
    public Enumeration<V> values() {
        return Collections.enumeration(storage.values());
    }
}
